package youcaihuaoa.weetop.com.vm.apply

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableField
import api.OtaServiceFactory
import api.UserServiceFactory
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.configs.PrefsManager
import com.robot.base.model.CustomProfileBean
import com.robot.base.model.FileBean
import com.robot.base.util.LiveDataBus
import com.robot.base.util.UriUtils
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.net.URLEncoder

class TrendApplyProfileViewModel(application: Application) : GLBaseViewModel(application) {

    val userName = ObservableField("")
    val departmentName = ObservableField("")
    val jobName = ObservableField("")
    val remake = ObservableField("")
    val companyName = ObservableField("")
    val uiEvent = UIEvent()
    var id = ""
    var zdy_form_id = ""
    var type = "99"

    val examine_remark = ObservableField("")


    //0 新申请 1 申请详情 2审批详情
    val status = ObservableField(0)

    val submitField = ObservableField("提交")
    val cancelField = ObservableField("取消")

    val complete = ObservableField(false)

    class UIEvent {
        val menuDataLiveEvent = SingleLiveEvent<CustomProfileBean>()
        val skipFileEvent = SingleLiveEvent<Void>()
        val confirmEvent = SingleLiveEvent<Void>()
        val updateFileEvent = SingleLiveEvent<List<FileBean>>()
    }

    init {
        userName.set(PrefsManager.getUserInfo().user_name)
        companyName.set(PrefsManager.getUserInfo().company_name)
        departmentName.set(PrefsManager.getUserInfo().department_name)
        jobName.set(PrefsManager.getUserInfo().job_name)
    }

    val toSkipFileCommand = BindingCommand<Any>(BindingAction {
        uiEvent.skipFileEvent.call()
    })

    val confirmCommand = BindingCommand<Any>(BindingAction {
        when (status.get()) {
            0, 1 -> {
                uiEvent.confirmEvent.call()
            }
            2 -> {
                examineUserVerify(1)
            }
        }

    })

    val cancelCommand = BindingCommand<Any>(BindingAction {
        when (status.get()) {
            0 -> {
                finish()
            }
            1 -> {
                examineUserRevoke()
            }
            2 -> {
                examineUserVerify(-1)
            }
        }
    })

    fun initData(status: Int, id: String, zdy_form_id: String) {
        this.status.set(status)
        this.id = id
        this.zdy_form_id = zdy_form_id
        when (status) {
            0 -> {
                submitField.set("提交")
                cancelField.set("返回")
                customInfo()
            }
            1 -> {
                submitField.set("重新发起")
                cancelField.set("撤销")
                applyUserInfo()
            }
            2 -> {
                submitField.set("同意")
                cancelField.set("拒绝")
                examineUserInfo()
            }
        }
    }

    fun applyUserInfo() {
        UserServiceFactory.applyUserInfo(
            mapOf(
                "template_type" to type,
                "model_type" to 2,
                "id" to id
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<CustomProfileBean>>(this) {
            override fun onNext(t: BaseResponse<CustomProfileBean>) {
                t.data ?: return
                userName.set(t.data.user_name)
                companyName.set(t.data.company_name)
                departmentName.set(t.data.department_name)
                jobName.set(t.data.job_name)

                remake.set(t.data.public_remark)
                complete.set(t.data.public_status == "1")
                t.data.str_data.forEach {
                    it.viewEnable = t.data.public_status != "1"
                }

                uiEvent.menuDataLiveEvent.postValue(t.data)
                val list = t.data.public_annex_path?.split(";")
                val fileBeanList = mutableListOf<FileBean>()
                list?.forEach {
                    val fileBean = FileBean()
                    fileBean.file_path = it
                    fileBean.file_type = it.substring(it.indexOf(".") + 1)
                    fileBeanList.add(fileBean)
                }
                uiEvent.updateFileEvent.postValue(fileBeanList)
            }
        })
    }

    fun examineUserInfo() {
        UserServiceFactory.examineUserInfo(
            mapOf(
                "template_type" to type,
                "model_type" to 2,
                "id" to id
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<CustomProfileBean>>(this) {
            override fun onNext(t: BaseResponse<CustomProfileBean>) {
                t.data ?: return
                userName.set(t.data.user_name)
                companyName.set(t.data.company_name)
                departmentName.set(t.data.department_name)
                jobName.set(t.data.job_name)

                remake.set(t.data.public_remark)
                complete.set(t.data.public_status == "1")
                t.data.str_data.forEach {
                    it.viewEnable = false
                }

                uiEvent.menuDataLiveEvent.postValue(t.data)
                val list = t.data.public_annex_path?.split(";")
                val fileBeanList = mutableListOf<FileBean>()
                list?.forEach {
                    val fileBean = FileBean()
                    fileBean.file_path = it
                    fileBean.file_type = it.substring(it.indexOf(".") + 1)
                    fileBeanList.add(fileBean)
                }
                uiEvent.updateFileEvent.postValue(fileBeanList)
            }
        })
    }

    fun customInfo() {
        val params = mapOf("id" to zdy_form_id)
        UserServiceFactory.customInfo(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<CustomProfileBean>>(this) {
                override fun onNext(t: BaseResponse<CustomProfileBean>) {
                    uiEvent.menuDataLiveEvent.postValue(t.data)
                }
            })
    }

    fun uploadFile(file: File) {
        val requestFile =
            file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
        val part = MultipartBody.Part.createFormData(
            "file",
            URLEncoder.encode(file.name, "UTF-8"),
            requestFile
        )
        OtaServiceFactory.uploadWhole(part)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<FileBean>>(this) {
                override fun onNext(t: BaseResponse<FileBean>) {
                    uiEvent.updateFileEvent.postValue(arrayListOf(t.data))
                }
            })
    }

    fun examineUserVerify(examine_status: Int) {
        val map = hashMapOf<String, Any>(
            "model_type" to 2,
            "template_type" to type,
            "examine_status" to examine_status
        )
        if (!TextUtils.isEmpty(examine_remark.get())) {
            map["examine_remark"] = examine_remark.get() ?: ""
        }

        if(!TextUtils.isEmpty(id)){
            map["id"] to id
        }
        UserServiceFactory.examineUserVerify(
            map
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                LiveDataBus.get().with(AppConstants.LiveKey.REFRESH_APPLY).postValue("1")
                finish()
            }
        })
    }

    fun examineUserRevoke() {
        val map = hashMapOf<String, Any>(
            "model_type" to 2,
            "template_type" to type
        )
        if (!TextUtils.isEmpty(examine_remark.get())) {
            map["revoke_remark"] = examine_remark.get() ?: ""
        }

        if(!TextUtils.isEmpty(id)){
            map["id"] to id
        }
        UserServiceFactory.examineUserRevoke(
            map
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                LiveDataBus.get().with(AppConstants.LiveKey.REFRESH_APPLY).postValue("1")
                finish()
            }
        })
    }

    /**
     * @param cz_type 操作类型：1新增；2再次提交（撤销和全部审批通过的表单不能再次提交）
     * @param str_data 其它信息(JSON)从前往后分别是： title：参数名称 value：参数值（用户填写的内容） status：是否必填：0否；1是；
     */
    fun templateWholeCustomAdd(
        cz_type: String,
        jbcs_fj_path: String,
        str_data: List<Map<String, String?>>
    ) {
        val map = hashMapOf<String, Any>(
            "zdy_form_id" to zdy_form_id,
            "cz_type" to cz_type,
            "jbcs_fj_path" to jbcs_fj_path
        )
        if (!TextUtils.isEmpty(remake.get())) {
            map["jbcs_remark"] = (remake.get() ?: "")
        }
        if (!str_data.isNullOrEmpty()) {
            map["str_data"] = JSON.toJSONString(str_data)
        }
        if(!TextUtils.isEmpty(id)){
            map["id"] to id
        }
        UserServiceFactory.templateWholeCustomAdd(map)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
                override fun onNext(t: BaseResponse<String>) {
                    ToastUtils.showShort("申请成功")
                    finish()
                }
            })
    }
}